﻿using System;
using System.Windows.Input;

namespace MyWpf.AppCommon.Commands
{
    public class DelegateCommand<T> : ICommand
    {
        private readonly Action<T> _execute;

        private readonly Predicate<object> _canExecute;

        public DelegateCommand(Action execute, Predicate<object> canExecute = null)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }

            _execute = obj => { execute(); };
            _canExecute = canExecute;
        }

        public DelegateCommand(Action<T> execute, Predicate<object> canExecute = null)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }

            _execute = execute;
            _canExecute = canExecute;
        }

        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute(parameter);
        }


        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }
}
